#include <stdarg.h>
#include "info.h"
#include "re.h"
#include "utils.h"

int wlog(char *file, const char *format, ...) {

   FILE *fp;
   char path[256], buffer[512], dateout[20];
   va_list l;

   va_start(l, format);
   vsprintf(buffer, format, l);
   va_end(l);

   sprintf(path, "logs/%s", file);

   fp = fopen(path, "a");
   if(fp==NULL) { printf("%s - na abriu\n", path); return -1; }

   mkdate("%d-%m %H:%M:%S", dateout);
   fprintf(fp,"%s: %s\n", dateout, buffer);

   fclose(fp);

}

void log_m(INFO *info) {

    RE *re;
    char *buffer[5];

    re = (RE *) malloc(sizeof(RE));

   if(matcher("^:([^ ]+)!([^ ]+)@[^ ]+ PRIVMSG ([^ ]+) :(.+)$", info->reciev, re)) {

      buffer[0] = re_copy(re,1, info->reciev);
      buffer[1] = re_copy(re,3, info->reciev);
      buffer[2] = re_copy(re,4, info->reciev);

      strtolower(buffer[1]);
      if(strcmp(buffer[1],info->nick)==0)
         wlog(buffer[0], "%s - %s", buffer[0], buffer[2]);
      else
         wlog(buffer[1], "%s - %s, %s", buffer[1], buffer[0], buffer[2]);

      free(buffer);

   }

   if(matcher("^:([^ ]+)!([^ ]+)@[^ ]+ JOIN :(.+)$", info->reciev, re)) {

      buffer[0] = re_copy(re,1, info->reciev);
      buffer[1] = re_copy(re,3, info->reciev);

      strtolower(buffer[1]);
      wlog(buffer[1], "%s entrou no canal...", buffer[0]);

   }

   free(re);

}

void onebot_m(INFO *info) {

   log_m(info);

}
